import 'package:flutter/material.dart';

import '../../model/model_extension.dart';
import '../class/dialog/choose_group.dart';
import '../model/model.dart';
import '../model/model_default.dart';
import '../tool/assets.dart';
import 'chart_page.dart';

abstract class BaseController extends StatefulWidget {
  late BaseControllerState kstate;
  BaseController({super.key});

  @override
  State<BaseController> createState() => kstate;
}

abstract class BaseControllerState<T extends BaseController> extends State<T> {
  ///group
  late final List<GroupModel> group_list;

  ///当前选中的group
  List<GroupModel> get select_group_list {
    return group_list.where(($0) => $0.select).toList();
  }

  ///用来标记页面的所有channel的select状态
  late List<bool> select_list;

  ///当前页面选中的channel通道
  ChannelModel get current_ch {
    return globalModel.select_ch_list[0];
  }

  @override
  void initState() {
    group_list = List.generate(4, (index) {
      ChannelModel ch1 = globalModel.ch_list[2 * index];
      ChannelModel ch2 = globalModel.ch_list[2 * index + 1];
      return GroupModel(name: 'Grouping\nCH${ch1.num}&${'${ch2.num}'}', ch1: ch1, ch2: ch2);
    });

    ///初始化选中状态，默认都没有选中
    select_list = globalModel.ch_list.map(($0) => $0.select).toList();

    super.initState();
  }

  ///子类需要实现这个方法来返回具体的页面内容
  Widget buildContent(BuildContext context);

  ///刷新视图
  void realod() {
    // if (globalModel.enable == false) {
    //   return;
    // }
    for (var group in group_list) {
      group.enable = globalModel.enable;
    }
    for (ChannelModel ch in globalModel.ch_list) {
      ch.enable = globalModel.enable;
      ch.high_pass!.enable = globalModel.enable;
      ch.low_pass!.enable = globalModel.enable;
      for (SignModel sign in ch.sign_list) {
        sign.enable = globalModel.enable;
      }
    }
    setState(() {});
  }

  ///选中通道，
  void select_ch(ChannelModel ch) {
    for (var $0 in globalModel.ch_list) {
      $0.select = ch.name == $0.name;
    }
    for (var group in select_group_list) {
      if (group.contain(ch)) {
        if (group.ch1?.name == ch.name) {
          group.ch2!.select = true;
        } else if (group.ch2?.name == ch.name) {
          group.ch1!.select = true;
        }
      }
    }
    select_list = globalModel.ch_list.map(($0) => $0.select).toList();
  }

  ///需要统一哪些数据，子类调用了unitChannel，自由决定统一哪些数据
  void copy(ChannelModel model, ChannelModel from);

  ///如果点的通道channel， 是某个group,并且这个group还是选中状态，就要统一group的两个channel数据
  bool unitChannel(ChannelModel ch) {
    select_ch(ch);

    ///如果当前有选中的group，并且group包含该channel 通道
    for (var group in select_group_list) {
      if (group.contain(ch)) {
        ///如果选中的channel是group的ch1
        if (group.ch1?.name == ch.name) {
          copy(group.ch2!, ch);
        } else if (group.ch2?.name == ch.name) {
          copy(group.ch1!, ch);
        }
        setState(() {});
        return true;
      }
    }
    setState(() {});
    return false;
  }

  ///点击group，相关处理
  void onclickGroup(GroupModel group) {
    ///弹出选择框
    ChooseGroup view = ChooseGroup(group: group);
    view.show(context);

    ///选择框回调
    view.onChoose = (_) {
      setState(() {
        ///如果优先选择ch1，则以ch1为目标，统一两个ch的值
        unitChannel(group.target_ch!);
      });
    };
  }

  ///长按 取消group的相关处理
  void onLongPressGroup(GroupModel group) {
    setState(() {
      group.select = false;
      group.ch1!.select = group.target_ch!.name == group.ch1!.name;
      group.ch2!.select = group.target_ch!.name == group.ch2!.name;
      group.target_ch = null;
      select_list = globalModel.ch_list.map(($0) => $0.select).toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    ///页面切换，恢复各自页面的channel记住状态
    for (var i = 0; i < select_list.length; i++) {
      globalModel.ch_list[i].select = select_list[i];
    }
    // double screenHeight = MediaQuery.of(context).size.height;
    // GlobalConfig.scaleH = screenHeight / 667.0;

    ///是否输入密码，禁止四个 页面的交互
    return AbsorbPointer(
      // absorbing: globalModel.enable == false,
      absorbing: false,

      child: SafeArea(
        child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constrians) {
          GlobalConfig.scaleH = constrians.maxHeight / 547.0;
          return SingleChildScrollView(
            // physics: NeverScrollableScrollPhysics(),
            padding: const EdgeInsets.only(left: 10, right: 10),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: double.infinity,
                  height: 118.0 / 547.0 * constrians.maxHeight,
                  // aspectRatio: 3.0 / 1.0,
                  child: ChartBG(ch: current_ch),
                ),

                /// 调用子类实现的内容
                buildContent(context),
              ],
            ),
          );
        }),
      ),
    );
  }
}
